package Auth;

import javax.annotation.Resource;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.sql.DataSource;
import javax.ejb.Stateless;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;
import java.io.Serializable;

/**
 * Created by IntelliJ IDEA.
 * User: mchebanenko
 * Date: 11-Aug-2010
 * Time: 4:12:25 PM
 * To change this template use File | Settings | File Templates.
 */


@Stateless
public class AuthenticationBean implements Authentication {

     public AuthenticationBean(){}

    //@Resource(mappedName="jdbc/Credit/DataSource")
    // USE FOR JBOSS
    @Resource(mappedName="java:jdbc/Credit/DataSource")
    private DataSource dataSource;
    private Connection connection;

    @PostConstruct
    public void initialize() {
        try {
            if (connection == null)
            connection = dataSource.getConnection();
        } catch (SQLException sqle) {
            sqle.printStackTrace();
        }
    }

     public int validateUser(String l,String pwd){

       if(l == null | pwd == null) return 0;

         Statement statement;
        try {
             statement = connection.createStatement();
             ResultSet res = statement.executeQuery("select pwd from users where login= '" + l + "'");
        if (res.next() ){

            if(res.getString("pwd").equals(pwd) ){
                if(l.equals("admin") ){
                    return 2;}
                else {
                    return 1;
                }
            }
            else {
                return 0;
            }

        } else   {
            return 0;
        }


         } catch (SQLException e) {
             e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
             return 0;
         }

     }

    @PreDestroy
    public void cleanup() {
        try {
        connection.close();
        } catch (Exception sqle) {
        sqle.printStackTrace();
        }

    }


}
